import React, { Component } from 'react';
import { GLOBAL } from '../../../config/global';
import { StyleSheet, Text, View, Image, TouchableOpacity, PixelRatio, FlatList, Alert, TextInput, Animated } from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Button } from '../../../components/form/button';
import { CURRENCY } from '../../../utils/helper';
import Dictionary from '../../../utils/dictionary';
import { RangTime } from '../../../component/common/RangTime.js';
import moment from 'moment';
import serviceAPI from './_common/serviceAPI';
import { OrderCommon } from '../_common/common';
import { ResourceBaoCpt } from './_components/ResourceBaoCpt';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
const scale = GLOBAL.SCALE;

export class TurnOrderList extends Component {
    static navigationOptions = ({ navigation, navigationOptions }) => {
        let { orderType } = navigation.state.params || {};
        return {
            title: `${orderType == 'P' ? '采购' : '销售'}转单管理`,
            headerTintColor: style.color.white,
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
            headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
            headerStyle: {
                elevation: 0,
                backgroundColor: style.color.themeColor,
                borderBottomWidth: 0
            },
            headerTitleStyle: {
                flex: 1,
                textAlign: 'center'
            }
        }
    }

    constructor(props) {
        super(props);
        const { choice } = props.navigation.state.params || {};
        this.state = {
            status: 'data',
            listData: [],
            refreshIcon: false,
            stateModal: false, // 状态弹框
            showTimeModal: false, // 时间选择
            alertShow: false,
            options: [],
            choice: choice || {}
        };
        this.stateIndex = 0;//初始化状态
        this.totalPage = 1;
        this.reload = true; // 判断是整个页面刷新还是下拉刷新
        let { longFrame, orderType } = props.navigation.state.params || {};
        console.log('props.navigation.state.params-0000', props.navigation.state.params)
        this.selectedFrame = longFrame || {};
        this.pageParams = {
            searchKey: null,
            beginDate: null, //开始时间
            endDate: null, //结束时间
            reportStatus: '', //状态
            pageNo: 1,
            pageSize: 5,
            orderType
        }
        this.stateData = null;
        this.dateObj = {
            startDate: moment(moment().subtract(1, 'months').calendar()).format('YYYY-MM-DD') || null,
            endDate: moment().format('YYYY-MM-DD') || null
        };
    }

    async componentWillMount() {
        await this.getSorage();
        await this._dictionaryFn();
        await this._initPage();
    }

    //获取业务组织
    async  getSorage() {
        const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
        const userInfo = JSON.parse(userInfoJson);
        this.setState({
            options: userInfo.corpInfoTOs || [],
            choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
        })
    }

    _initPage = async () => {
        this.setState({
            status: this.reload ? 'loading' : 'data',
            refreshIcon: !this.reload && this.pageParams.pageNo == '1'
        })
        this.pageParams.beginDate = this.dateObj.startDate;
        this.pageParams.endDate = this.dateObj.endDate;
        this.pageParams.reportStatus = this.stateData[this.stateIndex].dictKey;
        this.pageParams.corpId = this.state.choice.corpId;
        let res = await serviceAPI.getFindList(this.pageParams);
        console.log('页面获取-参数', this.pageParams);
        console.log('页面获取-res', res)
        if (res && res.rows) {
            this.totalPage = res.totalPage;
            this.setState({
                status: res.rows.length > 0 ? 'data' : 'empty',
                listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
                refreshIcon: false,
            })
        } else {
            this.setState({
                refreshIcon: false,
                status: 'error'
            })
        }
    }

    //获取状态数据字典
    _dictionaryFn = async () => {
        this.stateData = await Dictionary.get('UBMP_BID_REPORT_STATUS');
        console.log('this.stateData', this.stateData)
        this.stateData && this.stateData.forEach((item, index) => {
            if (item.dictKey == '0') {
                this.stateIndex = index;
            }
        })
    }


    // 下拉刷新
    _refresh = () => {
        this.pageParams.pageNo = 1;
        this.reload = false;
        this._initPage();
    }

    // 刷新
    _reloadPage = () => {
        this.pageParams.pageNo = 1;
        this.reload = true;
        this._initPage();
    }

    // 加载更多
    _loadMore = () => {
        if (this.totalPage > this.pageParams.pageNo) {
            this.pageParams.pageNo++;
            this.reload = false;
            this._initPage();
        }
    }

    // 搜索View
    _renderSearchWarp = () => {
        const searchIcon = require('../../../imgs/global/whiteSearch.png');
        return (
            <View style={styles.filterWrap}>
                <View>
                    <Image source={searchIcon} style={styles.searchIcon} />
                    <TextInput
                        ref="orderKeywordsInput"
                        style={styles.searchInput}
                        underlineColorAndroid='transparent'
                        placeholder={"商品名称/资源包编号"}
                        placeholderTextColor="rgba(255, 255, 255, .8)"
                        maxLength={30}
                        returnKeyType={'search'}
                        defaultValue={this.pageParams.searchKey}
                        onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
                        onSubmitEditing={() => { this._refresh() }}
                    />
                </View>
            </View>
        )
    }

    _renderListItem = (data) => {
        return <ResourceBaoCpt itemData={data.item || {}} choice={this.state.choice} />
    }

    //选择状态 回掉函数
    _stateCallBack = (index) => {
        this.stateIndex = index;
        this.setState({
            stateModal: false
        }, () => {
            //页面重新初始化
            this._refresh();
        })
    }

    //选择状态 弹框关闭
    _closeModal = () => {
        this.setState({
            stateModal: false
        })
    }

    //打开模态框
    _selecOpen = () => {
        this.setState({
            stateModal: true
        })
    }

    //打开时间弹框
    _timeOpen = () => {
        this.setState({
            showTimeModal: true
        })
    }

    // 选择时间
    _resultCall = (resultData) => {
        this.dateObj.startDate = resultData.startTime || '';
        this.dateObj.endDate = resultData.endTime;
        this.setState({ showTimeModal: false, }, () => {
            this._refresh();
        })
    }


    render() {
        let { status, listData, refreshIcon, stateModal, showTimeModal, alertShow, choice, options } = this.state || {};
        return (
            <View style={styles.container}>
                {options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
                <View style={styles.headBox}>
                    {this._renderSearchWarp()}
                </View>
                <View style={styles.statusBox}>
                    <TouchableOpacity style={styles.statusItem} onPress={this._selecOpen}>
                        {this.stateData && <Text style={styles.statusTextSelect}>{(this.stateData[this.stateIndex] && this.stateData[this.stateIndex].dictName) || ''}</Text>}
                        <Image source={require('../../../imgs/select.png')} />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.statusItem} onPress={this._timeOpen}>
                        <Text style={styles.statusItemText}>{this.dateObj.startDate || ''}</Text>
                        <Text style={[styles.statusItemText, styles.statusItemTextActive]}>至</Text>
                        <Text style={styles.statusItemText}>{this.dateObj.endDate || ''}</Text>
                        {/* <Image style={styles.statusItemImg} source={require('../../../imgs/customer/blueRorrow.png')} /> */}
                        <Image source={require('../../../imgs/time.png')} style={styles.statusTimeImg}></Image>
                    </TouchableOpacity>
                </View>
                {
                    status == 'data' ? (
                        <View style={{ flex: 1 }}>
                            <View style={{ marginTop: 10 * scale }}>
                                <FlatList
                                    data={listData}
                                    renderItem={this._renderListItem}
                                    refreshing={refreshIcon}
                                    onRefresh={() => { this._refresh() }}
                                    onEndReachedThreshold={0.1}
                                    onEndReached={() => { this._loadMore() }}
                                />
                            </View>
                        </View>
                    ) : null
                }
                {
                    status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无数据" onErrorPress={this._reloadPage} />) : null
                }
                {/* 状态弹框 */}
                <Common type="modal" demoData={(
                    <Common type="listRadio" selectIndex={this.stateIndex} title="选择订单类型" listData={this.stateData} selectCallBack={this._stateCallBack} />
                )} isVisible={stateModal} closeCallballFn={() => { this._closeModal({ stateModal }) }} />
                {/* 时间弹框 */}
                {
                    showTimeModal ? <RangTime isClear={true} isVisible={true} markedDates={null} startTime={this.dateObj.startDate} endTime={this.dateObj.endDate} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
                }

                <SlideSelect alertShow={alertShow} options={options}
                    select={(val) => {
                        this.setState({ choice: val || options[0], alertShow: false }, () => {
                            this._reloadPage();
                        })
                    }}
                    unselect={() => {
                        this.setState({ alertShow: false })
                    }} />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#EEF1FA',
        position: 'relative'
    },
    headBox: {
        height: 80 * scale,
        backgroundColor: style.color.themeColor,
    },
    statusBox: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 60 * scale,
    },
    statusItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 12 * scale,
        marginRight: 12 * scale
    },
    statusTextSelect: {
        color: '#0E7FFD',
        fontWeight: 'bold',
        marginRight: 10 * scale,
        fontSize: 14 * scale
    },
    statusItemText: {
        fontSize: 12 * scale,
        // color: '#fff'
    },
    statusItemTextActive: {
        paddingLeft: 3 * scale,
        paddingRight: 3 * scale
    },
    statusItemImg: {
        marginLeft: 5 * scale,
        // tintColor: '#fff'
    },
    searchWrap: {
        width: '100%',
        height: 66 * scale,
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
    },
    btnWarp: {
        height: 72 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-around',
    },
    searchInput: {
        height: 36 * scale,
        width: 270 * scale,
        paddingLeft: 80 * scale,
        paddingRight: 12 * scale,
        backgroundColor: 'rgba(255, 255, 255, .18)',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 0,
        position: 'relative',
        borderRadius: 8 * scale,
        color: '#fff',
    },
    searchIcon: {
        width: 20 * scale,
        height: 20 * scale,
        position: 'absolute',
        left: 40 * scale,
        top: 8 * scale,
        zIndex: 9,
        opacity: 0.8,
    },
    filterWrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: style.color.themeColor,
        paddingTop: 14 * scale,
        paddingBottom: 14 * scale,
    },
    statusTimeImg: {
        tintColor: style.color.themeColor,
        marginLeft: 5 * scale,
        width: 14 * scale,
        height: 16 * scale
    },
})